////////////////////////////////////////////////////////////////////////////////////////
//
// JSimpleSim - A machine language simulator based on SimpSim by Anne-Gert Bultena.
//
// Copyright (C) 2008 Gerardo Camorlinga, Ryan Fitzgerald, and RJ Gordon
//
// This file is part of JSimpleSim.
//
// JSimpleSim is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// JSimpleSim is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with JSimpleSim.  If not, see <http://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////////////////////

/*
 * EditorView.java
 *
 * Created on September 25, 2008, 4:21 PM
 */
package jsimplesim.view;

import jsimplesim.assembler.Assembler;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import org.fife.ui.rsyntaxtextarea.*;
import org.fife.ui.rtextarea.*;
import java.io.*;
import java.net.URL;
import java.util.*;

import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.*;
import javax.swing.filechooser.*;

import org.apache.log4j.*;

/**
 * 
 * @author f08maroon
 */
public class EditorView extends JFrame implements SyntaxConstants {

    /**
	 * 
	 */
	private static final long serialVersionUID = 7079236513036602484L;
	static Logger logger = Logger.getLogger(EditorView.class);
    private boolean isFirstSaved;
    private File saveFile;
    private RTextScrollPane scrollPane;
    private RSyntaxTextArea textArea;
    //private javax.swing.JMenu editMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenu assembleItem;
    //private javax.swing.JMenu errorItem;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem helpInstructionsItem;
    @SuppressWarnings("unused")
	private javax.swing.JMenuItem helpSyntaxItem;
    private javax.swing.JMenuItem fileSaveItem;
    private javax.swing.JMenuItem fileSaveAsItem;
    private javax.swing.JMenuItem filePrintItem;
    private javax.swing.JMenuItem fileExitItem;
    //private javax.swing.JMenuItem editMenuCutItem;
    //private javax.swing.JMenuItem editMenuCopyItem;
    //private javax.swing.JMenuItem editMenuPasteItem;
    //private javax.swing.JMenuItem editMenuSelectAllItem;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    @SuppressWarnings("unused")
	private javax.swing.JSeparator jSeparator3;
    @SuppressWarnings("unused")
	private javax.swing.JSeparator jSeparator4;
    private javax.swing.JMenuItem fileOpenItem;
    private javax.swing.JList errorConsole;
    private JSimpleSimView jst;
    private DefaultListModel errorModel;

    // End of variables declaration
    /** Creates new form EditorView */
    public EditorView() {
        this.setVisible(true);

        // setupEditor();
        String test = null;
        this.isFirstSaved = true;
        initComponents(test);
        this.setSize(600, 500);

    }

    /**
     *
     * @param file
     * @param jssv
     */
    public EditorView(String file, JSimpleSimView jssv) {
        logger.debug("Inside editor constructor with file");
        jst = jssv;
        this.setVisible(true);
        this.isFirstSaved = true;
        initComponents(file);
        this.setSize(600, 500);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor. DONT UNCOMMENT THIS CODE IN NET- BEANS
     * otherwise the text area won't work!!!!!!!!! Once we move to Eclipse we
     * can delete this altogether, but first need to finish up the gui...
     */
    /*
     * @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed"
     * desc="Generated Code">                                       
     * initComponents() {
     * 
     * jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new
     * javax.swing.JScrollPane(); errorConsole = new javax.swing.JList();
     * jMenuBar1 = new javax.swing.JMenuBar(); fileMenu = new
     * javax.swing.JMenu(); fileOpenItem = new javax.swing.JMenuItem();
     * fileSaveItem = new javax.swing.JMenuItem(); fileSaveAsItem = new
     * javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator();
     * filePrintItem = new javax.swing.JMenuItem(); jSeparator2 = new
     * javax.swing.JSeparator(); fileExitItem = new javax.swing.JMenuItem();
     * editMenu = new javax.swing.JMenu(); jMenuItem6 = new
     * javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem();
     * jMenuItem8 = new javax.swing.JMenuItem(); jSeparator3 = new
     * javax.swing.JSeparator(); jMenuItem9 = new javax.swing.JMenuItem();
     * jSeparator4 = new javax.swing.JSeparator(); assembleItem = new
     * javax.swing.JMenu(); errorItem = new javax.swing.JMenu(); helpMenu = new
     * javax.swing.JMenu(); helpInstructionsItem = new javax.swing.JMenuItem();
     * helpSyntaxItem = new javax.swing.JMenuItem();
     * 
     * setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
     * org.jdesktop.application.ResourceMap resourceMap =
     * org.jdesktop.application.Application.getInstance(jsimplesim.JSimpleSimApp.class).getContext().getResourceMap(EditorView.class);
     * setTitle(resourceMap.getString("Form.title")); // NOI18N
     * setMinimumSize(new java.awt.Dimension(800, 600)); setName("Form"); //
     * NOI18N
     * 
     * jPanel1.setName("jPanel1"); // NOI18N
     * 
     * jScrollPane1.setName("jScrollPane1"); // NOI18N
     * 
     * errorConsole.setToolTipText(resourceMap.getString("errorConsole.toolTipText")); //
     * NOI18N errorConsole.setName("errorConsole"); // NOI18N
     * jScrollPane1.setViewportView(errorConsole);
     * 
     * javax.swing.GroupLayout jPanel1Layout = new
     * javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout);
     * jPanel1Layout.setHorizontalGroup(
     * jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     * .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27)
     * .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 570,
     * javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(154,
     * Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup(
     * jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     * .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
     * jPanel1Layout.createSequentialGroup() .addContainerGap(57,
     * Short.MAX_VALUE) .addComponent(jScrollPane1,
     * javax.swing.GroupLayout.PREFERRED_SIZE, 122,
     * javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) );
     * 
     * jMenuBar1.setName("jMenuBar1"); // NOI18N
     * 
     * fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
     * fileMenu.setName("fileMenu"); // NOI18N fileMenu.addActionListener(new
     * java.awt.event.ActionListener() { public void
     * actionPerformed(java.awt.event.ActionEvent evt) {
     * fileMenuActionPerformed(evt); } });
     * 
     * javax.swing.ActionMap actionMap =
     * org.jdesktop.application.Application.getInstance(jsimplesim.JSimpleSimApp.class).getContext().getActionMap(EditorView.class,
     * this); fileOpenItem.setAction(actionMap.get("openItem")); // NOI18N
     * fileOpenItem.setName("fileOpenItem"); // NOI18N
     * fileMenu.add(fileOpenItem);
     * 
     * fileSaveItem.setAction(actionMap.get("saveItem")); // NOI18N
     * fileSaveItem.setText(resourceMap.getString("fileSaveItem.text")); //
     * NOI18N fileSaveItem.setName("fileSaveItem"); // NOI18N
     * fileMenu.add(fileSaveItem);
     * 
     * fileSaveAsItem.setText(resourceMap.getString("fileSaveAsItem.text")); //
     * NOI18N fileSaveAsItem.setName("fileSaveAsItem"); // NOI18N
     * fileSaveAsItem.addActionListener(new java.awt.event.ActionListener() {
     * public void actionPerformed(java.awt.event.ActionEvent evt) {
     * fileSaveAsItemActionPerformed(evt); } }); fileMenu.add(fileSaveAsItem);
     * 
     * jSeparator1.setName("jSeparator1"); // NOI18N fileMenu.add(jSeparator1);
     * 
     * filePrintItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P,
     * java.awt.event.InputEvent.CTRL_MASK));
     * filePrintItem.setText(resourceMap.getString("filePrintItem.text")); //
     * NOI18N filePrintItem.setName("filePrintItem"); // NOI18N
     * fileMenu.add(filePrintItem);
     * 
     * jSeparator2.setName("jSeparator2"); // NOI18N fileMenu.add(jSeparator2);
     * 
     * fileExitItem.setAction(actionMap.get("closeFrame")); // NOI18N
     * fileExitItem.setText(resourceMap.getString("fileExitItem.text")); //
     * NOI18N fileExitItem.setName("fileExitItem"); // NOI18N
     * fileMenu.add(fileExitItem);
     * 
     * jMenuBar1.add(fileMenu);
     * 
     * editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
     * editMenu.setName("editMenu"); // NOI18N
     * 
     * jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X,
     * java.awt.event.InputEvent.CTRL_MASK));
     * jMenuItem6.setText(resourceMap.getString("jMenuItem6.text")); // NOI18N
     * jMenuItem6.setName("jMenuItem6"); // NOI18N editMenu.add(jMenuItem6);
     * 
     * jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C,
     * java.awt.event.InputEvent.CTRL_MASK));
     * jMenuItem7.setText(resourceMap.getString("jMenuItem7.text")); // NOI18N
     * jMenuItem7.setName("jMenuItem7"); // NOI18N editMenu.add(jMenuItem7);
     * 
     * jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V,
     * java.awt.event.InputEvent.CTRL_MASK));
     * jMenuItem8.setText(resourceMap.getString("jMenuItem8.text")); // NOI18N
     * jMenuItem8.setName("jMenuItem8"); // NOI18N editMenu.add(jMenuItem8);
     * 
     * jSeparator3.setName("jSeparator3"); // NOI18N editMenu.add(jSeparator3);
     * 
     * jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,
     * java.awt.event.InputEvent.CTRL_MASK));
     * jMenuItem9.setText(resourceMap.getString("jMenuItem9.text")); // NOI18N
     * jMenuItem9.setName("jMenuItem9"); // NOI18N editMenu.add(jMenuItem9);
     * 
     * jSeparator4.setName("jSeparator4"); // NOI18N editMenu.add(jSeparator4);
     * 
     * jMenuBar1.add(editMenu);
     * 
     * assembleItem.setText(resourceMap.getString("assembleItem.text")); //
     * NOI18N assembleItem.setName("assembleItem"); // NOI18N
     * jMenuBar1.add(assembleItem);
     * 
     * errorItem.setText(resourceMap.getString("errorItem.text")); // NOI18N
     * errorItem.setName("errorItem"); // NOI18N jMenuBar1.add(errorItem);
     * 
     * helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
     * helpMenu.setName("helpMenu"); // NOI18N
     * 
     * helpInstructionsItem.setText(resourceMap.getString("helpInstructionsItem.text")); //
     * NOI18N helpInstructionsItem.setName("helpInstructionsItem"); // NOI18N
     * helpMenu.add(helpInstructionsItem);
     * 
     * helpSyntaxItem.setText(resourceMap.getString("helpSyntaxItem.text")); //
     * NOI18N helpSyntaxItem.setName("helpSyntaxItem"); // NOI18N
     * helpMenu.add(helpSyntaxItem);
     * 
     * jMenuBar1.add(helpMenu);
     * 
     * setJMenuBar(jMenuBar1);
     * 
     * javax.swing.GroupLayout layout = new
     * javax.swing.GroupLayout(getContentPane());
     * getContentPane().setLayout(layout); layout.setHorizontalGroup(
     * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     * .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
     * javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) );
     * layout.setVerticalGroup(
     * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     * .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
     * layout.createSequentialGroup() .addContainerGap(271, Short.MAX_VALUE)
     * .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
     * javax.swing.GroupLayout.DEFAULT_SIZE,
     * javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) );
     * 
     * pack(); }// </editor-fold>                        
     * 
     * private void fileMenuActionPerformed(java.awt.event.ActionEvent evt)
     * {                                                                        
     * here: }                                        
     * 
     * private void fileSaveAsItemActionPerformed(java.awt.event.ActionEvent
     * evt) {                                                                
     * handling code here: JFileChooser fc = new JFileChooser();
     * fc.showSaveDialog(this); }                                              
     */
    /*
     * // Variables declaration - do not modify                             
     * javax.swing.JMenu assembleItem; private javax.swing.JMenu editMenu;
     * private javax.swing.JList errorConsole; private javax.swing.JMenu
     * errorItem; private javax.swing.JMenuItem fileExitItem; private
     * javax.swing.JMenu fileMenu; private javax.swing.JMenuItem fileOpenItem;
     * private javax.swing.JMenuItem filePrintItem; private
     * javax.swing.JMenuItem fileSaveAsItem; private javax.swing.JMenuItem
     * fileSaveItem; private javax.swing.JMenuItem helpInstructionsItem; private
     * javax.swing.JMenu helpMenu; private javax.swing.JMenuItem helpSyntaxItem;
     * private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem
     * jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private
     * javax.swing.JMenuItem jMenuItem8; private javax.swing.JMenuItem
     * jMenuItem9; private javax.swing.JPanel jPanel1; private
     * javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator
     * jSeparator1; private javax.swing.JSeparator jSeparator2; private
     * javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator
     * jSeparator4; // End of variables declaration                   
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    /**
     * To add more components(buttons, labels, etc.) first add them in the
     * Design view, put them where you want them then come back to the source
     * view, and copy the newly generated code for the components you just added
     * and copy them to this method. Once we move to Eclipse we won't have to
     * worry about it anymore.
     */
    private void initComponents(String file) {

        jPanel1 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        fileOpenItem = new javax.swing.JMenuItem();
        fileSaveItem = new javax.swing.JMenuItem();
        fileSaveAsItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        filePrintItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        fileExitItem = new javax.swing.JMenuItem();
        //editMenu = new javax.swing.JMenu();
        //editMenuCutItem = new javax.swing.JMenuItem();
        //editMenuCopyItem = new javax.swing.JMenuItem();
        //editMenuPasteItem = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        //editMenuSelectAllItem = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        assembleItem = new javax.swing.JMenu();
        //errorItem = new javax.swing.JMenu();
        helpMenu = new javax.swing.JMenu();
        helpInstructionsItem = new javax.swing.JMenuItem();
        helpSyntaxItem = new javax.swing.JMenuItem();
        // jScrollPane1 = new javax.swing.JScrollPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jsimplesim.JSimpleSimApp.class).getContext().getResourceMap(EditorView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N

        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N

        fileMenu.setName("fileMenu"); // NOI18N

        fileMenu.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jsimplesim.JSimpleSimApp.class).getContext().getActionMap(EditorView.class, this);
        fileOpenItem.setAction(actionMap.get("openItem")); // NOI18N

        fileOpenItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
                java.awt.event.KeyEvent.VK_O,
                java.awt.event.InputEvent.CTRL_MASK));
        fileOpenItem.setName("fileOpenItem"); // NOI18N

        fileMenu.add(fileOpenItem);

        fileSaveItem.setAction(actionMap.get("saveItem")); // NOI18N

        fileSaveItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
                java.awt.event.KeyEvent.VK_S,
                java.awt.event.InputEvent.CTRL_MASK));
        fileSaveItem.setText(resourceMap.getString("fileSaveItem.text")); // NOI18N

        fileSaveItem.setName("fileSaveItem"); // NOI18N

        fileMenu.add(fileSaveItem);

        fileSaveAsItem.setText(resourceMap.getString("fileSaveAsItem.text")); // NOI18N

        fileSaveAsItem.setName("fileSaveAsItem"); // NOI18N

        fileSaveAsItem.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileSaveAsItemActionPerformed(evt);
            }
        });
        fileMenu.add(fileSaveAsItem);

        jSeparator1.setName("jSeparator1"); // NOI18N

        fileMenu.add(jSeparator1);

        filePrintItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
                java.awt.event.KeyEvent.VK_P,
                java.awt.event.InputEvent.CTRL_MASK));
        filePrintItem.setText(resourceMap.getString("filePrintItem.text")); // NOI18N

        filePrintItem.setAction(actionMap.get("Print"));

        filePrintItem.setName("filePrintItem"); // NOI18N

        fileMenu.add(filePrintItem);

        jSeparator2.setName("jSeparator2"); // NOI18N

        fileMenu.add(jSeparator2);

        fileExitItem.setAction(actionMap.get("closeFrame")); // NOI18N

        fileExitItem.setText(resourceMap.getString("fileExitItem.text")); // NOI18N

        fileExitItem.setName("fileExitItem"); // NOI18N

        fileMenu.add(fileExitItem);

        jMenuBar1.add(fileMenu);
        /*
        editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
        
        editMenu.setName("editMenu"); // NOI18N
        
        editMenuCutItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
        java.awt.event.KeyEvent.VK_X,
        java.awt.event.InputEvent.CTRL_MASK));
        editMenuCutItem.setText("Cut"); // NOI18N
        
        editMenuCutItem.setName("Cut"); // NOI18N
        
        editMenu.add(editMenuCutItem);
        
        editMenuCopyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
        java.awt.event.KeyEvent.VK_C,
        java.awt.event.InputEvent.CTRL_MASK));
        editMenuCopyItem.setText("Copy"); // NOI18N
        
        editMenuCopyItem.setName("Copy"); // NOI18N
        
        editMenu.add(editMenuCopyItem);
        
        editMenuPasteItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
        java.awt.event.KeyEvent.VK_V,
        java.awt.event.InputEvent.CTRL_MASK));
        editMenuPasteItem.setText("Paste"); // NOI18N
        
        editMenuPasteItem.setName("Paste"); // NOI18N
        
        editMenu.add(editMenuPasteItem);
        
        jSeparator3.setName("jSeparator3"); // NOI18N
        
        editMenu.add(jSeparator3);
        
        editMenuSelectAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
        java.awt.event.KeyEvent.VK_A,
        java.awt.event.InputEvent.CTRL_MASK));
        editMenuSelectAllItem.setText("Select All"); // NOI18N
        
        editMenuSelectAllItem.setName("SelectAll"); // NOI18N
        
        editMenu.add(editMenuSelectAllItem);
        
        jSeparator4.setName("jSeparator4"); // NOI18N
        
        editMenu.add(jSeparator4);
        
        jMenuBar1.add(editMenu);
         */
        assembleItem.setText(resourceMap.getString("assembleItem.text")); // NOI18N

        assembleItem.setName("assembleItem"); // NOI18N

        JMenuItem assembler = new JMenuItem();

        assembler.setText("Assemble");

        assembler.setName("assemblerItem");

        assembler.setAction(actionMap.get("Assemble"));

        assembleItem.add(assembler);

        jMenuBar1.add(assembleItem);

        //errorItem.setText(resourceMap.getString("errorItem.text")); // NOI18N

        //errorItem.setName("errorItem"); // NOI18N

        //jMenuBar1.add(errorItem);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N

        helpMenu.setName("helpMenu"); // NOI18N

        helpInstructionsItem.setText(resourceMap.getString("helpInstructionsItem.text")); // NOI18N

        helpInstructionsItem.setName("helpInstructionsItem"); // NOI18N

        String helpHS = "helpset.hs";

        HelpSet hs;
        try {
            ClassLoader cl = JSimpleSimView.class.getClassLoader();
            URL hsURL = HelpSet.findHelpSet(cl, helpHS);
            logger.debug("hsURl: " + hsURL.toString() + ", " + hsURL.toExternalForm());
            hs = new HelpSet(null, hsURL);
        } catch (Exception ee) {
// Say what the exception really is
            System.out.println("HelpSet " + ee.getMessage());
            System.out.println("HelpSet " + helpHS + " not found");
            return;
        }
        HelpBroker hb = hs.createHelpBroker();
        helpInstructionsItem.addActionListener(new CSH.DisplayHelpFromSource(hb));

        helpMenu.add(helpInstructionsItem);

        jMenuBar1.add(helpMenu);

        setJMenuBar(jMenuBar1);

        jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
        textArea = createTextArea(file);
        scrollPane = new RTextScrollPane(500, 300, textArea, true);

        setJMenuBar(jMenuBar1);
        // this.setL

        JPanel bottomPane = new JPanel();

        JButton assemble = new JButton("Assemble");
        assemble.setAction(actionMap.get("Assemble"));
        // assemble.setActionCommand("assembly");

        bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.X_AXIS));

        JScrollPane jScrollPane1 = new JScrollPane();
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        setErrorModel(new DefaultListModel());
        // errorModel.addElement("test1");
        // errorModel.addElement("test2");

        setErrorConsole(new JList(getErrorModel()));
        getErrorConsole().setToolTipText(
                resourceMap.getString("errorConsole.toolTipText")); // NOI18N

        getErrorConsole().setName("errorConsole"); // NOI18N

        this.getErrorConsole().setForeground(Color.RED);

        getErrorConsole().setVisible(true);
        jScrollPane1.setVisible(true);
        jScrollPane1.setViewportView(getErrorConsole());

        //Double click error console
        errorConsole.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                JList list = (JList) evt.getSource();
                if (evt.getClickCount() == 2) {          // Double-click
                    // Get item index
                    int index = list.locationToIndex(evt.getPoint());
                    highlightErrorLine(index);
                }

            }

            // This method is incomplete. All it does so far is put the line number in an int
            // when you double click an error message
            private void highlightErrorLine(int index) {
                String errorMessage = errorConsole.getModel().getElementAt(index) + "";

                // The line number begins at index 5 in all of our error messages
                String ln = errorMessage.charAt(5) + "";

                // This loop gets the rest of the numbers, if any, until the : is reached
                int i = 6;
                while (errorMessage.charAt(i) != ':') {
                    ln = ln + errorMessage.charAt(i);
                    i++;
                }

                @SuppressWarnings("unused")
				int lineNumber = Integer.parseInt(ln);
                //System.out.println(lineNumber);
                
            }
        });


        // jPanel1.setSize(600, 500);
        bottomPane.add(jScrollPane1);
        bottomPane.add(Box.createRigidArea(new Dimension(10, 0)));
        bottomPane.add(assemble);
        bottomPane.add(Box.createRigidArea(new Dimension(10, 0)));
        jPanel1.add(scrollPane);
        jPanel1.add(bottomPane);
        getContentPane().add(jPanel1);

        pack();
        System.out.print("Done with init");
    }//

    /**
     * A helper method that initializes our TextArea.
     * 
     * @return textArea - the RSyntaxTextArea object
     */
    private RSyntaxTextArea createTextArea(String file) {
        RSyntaxTextArea aTextArea = new RSyntaxTextArea();
        aTextArea.restoreDefaultSyntaxHighlightingColorScheme();
        aTextArea.setSyntaxEditingStyle(RSyntaxTextArea.ASSEMBLER_X86_SYNTAX_STYLE);
        aTextArea.setText(file);
        return aTextArea;
    }

    @SuppressWarnings("unused")
	private RSyntaxTextArea createTextArea() {
        RSyntaxTextArea aTextArea = new RSyntaxTextArea();
        aTextArea.restoreDefaultSyntaxHighlightingColorScheme();
        aTextArea.setSyntaxEditingStyle(RSyntaxTextArea.ASSEMBLER_X86_SYNTAX_STYLE);
        return aTextArea;
    }

    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void fileSaveAsItemActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "ASM Files", "asm");
        fc.setFileFilter(filter);
        fc.addChoosableFileFilter(filter);
        if (evt.getSource() == fileSaveAsItem) {
            int returnVal = fc.showSaveDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                String fileName = file.getName();
                // System.out.println("File selected: " + file.getName());
                if (file.exists()) {
                    writeToFile(file);

                } else {
                    fileName = file.getAbsolutePath();
                    if ((fileName.toLowerCase()).contains(".asm")) {
                        File newFile = createFile(fileName);
                        writeToFile(newFile);
                    } else {
                        File newFile = createFile(fileName + ".asm");
                        writeToFile(newFile);
                    }


                }
            }
        }

    }

    private void writeToFile(File fileName) {
        try {

            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));

            out.write(textArea.getText());
            out.close();
        } catch (Exception e) {
            logger.error("Failed to write the file.", e);
        }
    }

    private File createFile(String fileName) {
        return new File(fileName);

    }

    private void load() {

        final JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "ASM Files", "asm");
        fc.setFileFilter(filter);
        fc.addChoosableFileFilter(filter);
        int returnVal;
        returnVal = fc.showOpenDialog(EditorView.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            this.saveFile = file;
            logger.debug("SaveFile set to: " + file.getName());
            this.isFirstSaved = false;

            try {
                String str = "";
                Scanner sc = new Scanner(file);
                while (sc.hasNextLine()) {
                    str += sc.nextLine() + "\n";

                }

                textArea.setText(str);
            } catch (Exception e) {
            }

        // This is where a real application would open the file.
        // log.append("Opening: " + file.getName() + "." + newline);
        } else {
            // log.append("Open command cancelled by user." + newline);
        }

    }

    /**
     *
     */
    @org.jdesktop.application.Action
    public void openItem() {
        this.load();
    }

    /**
     *
     */
    @org.jdesktop.application.Action
    public void saveItem() {
        if (this.isFirstSaved) {
            logger.debug("the first save...");
            this.save();
        } else {
            //logger.debug("not the first save...the saveFile = " + saveFile.getName());
            this.writeToFile(this.saveFile);
        }

    }

    private void save() {
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "ASM Files", "asm");
        fc.setFileFilter(filter);
        fc.addChoosableFileFilter(filter);

        int returnVal = fc.showSaveDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.isFirstSaved = false;
            File file = fc.getSelectedFile();
            String fileName = file.getName();
            // System.out.println("File selected: " + file.getName());
            if (file.exists()) {
                this.writeToFile(file);
                this.saveFile = file;

            } else {
                fileName = file.getAbsolutePath();
                if ((fileName.toLowerCase()).contains(".asm")) {
                    File newFile = createFile(fileName);
                    writeToFile(newFile);
                } else {
                    File newFile = createFile(fileName + ".asm");
                    writeToFile(newFile);
                }
            //File newFile = createFile(fileName);

            //this.writeToFile(newFile);
            //this.saveFile = newFile;
            }
        } else {
        }
    }

    /**
     *
     */
    @org.jdesktop.application.Action
    public void closeFrame() {
        this.dispose();
    }

    @org.jdesktop.application.Action
    public void Print() {
        logger.info("Going to print some docs");
        try {
            boolean complete = this.textArea.print();
            if (complete) {
                /* show a success message  */
            } else {
                /*show a message indicating that printing was cancelled */
            }
        } catch (PrinterException pe) {
            /* Printing failed, report to the user */
        }
    }

    /**
     *
     */
    @org.jdesktop.application.Action
    public void Assemble() {
        logger.info("inside the assembly action after pushing button");
        this.getErrorModel().clear();

        String docText = textArea.getText();
        docText = docText.trim();
        if (!docText.equals("")) {
            Assembler apo = new Assembler(docText);
            byte[] temp = apo.getInstructions();
            if (!apo.getError()) {
                if (temp != null) {
                    jst.getMemModel().resetBuffer(temp);
                    Disassemble.run(jst.getMemModel(), jst);
                    this.toBack();
                    jst.getFrame().toFront();
                }
            } else {
                // there were errors so we have to report them.
                this.listErrors(apo.getErrors());
            }

        }
    }

    private void listErrors(ArrayList<String> errors) {
        // TODO Auto-generated method stub
        for (String str : errors) {
            this.getErrorModel().addElement(str);
        }
    }

    /**
     * @param errorModel
     *            the errorModel to set
     */
    public void setErrorModel(DefaultListModel errorModel) {
        this.errorModel = errorModel;
    }

    /**
     * @return the errorModel
     */
    public DefaultListModel getErrorModel() {
        return errorModel;
    }

    /**
     * @param errorConsole
     *            the errorConsole to set
     */
    public void setErrorConsole(javax.swing.JList errorConsole) {
        this.errorConsole = errorConsole;
    }

    /**
     * @return the errorConsole
     */
    public javax.swing.JList getErrorConsole() {
        return errorConsole;
    }            // Add a listener for mouse clicks
}
    
    
    
